package com.wangbo.restTemplate.camviNew;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.File;

public class TestCamviNew {
    public static final String BASE_URL = "http://120.92.137.180:8081/api";
    public static final String PERSON_IDENTIFY = "/person/identify";
    public static final String PERSON_ENROLL = "/person/enroll";
    public static final String PERSON_ENROLL_FEATURE = "/person/enrollFeature";
    public static final String PERSON_DELETE = "/person/delete";
    public static final String GET_FACE_FEATURE = "/person/getFaceFeature";
    public static final String FACE_DETECT = "/face/detect";
    public static final String PERSON_GET = "/person/get";
    public static final String Authorization = "yeMNBVAY2guSbo3Ogmu318Ah6F97g81O";
    public static final String CUC_KEY = "szlx";

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplateBuilder().errorHandler(new DefaultResponseErrorHandler(){
            /**
             * 设置RestTemplate自带的异常处理器不做异常处理
             **/
            @Override
            public void handleError(ClientHttpResponse response) {
            }
        }).build();

//        byte[] bytes = FileUtil.readBytes("D:\\temp\\big_2.jpg");

        // 人员批量搜索
        File dir = new File("D:\\test");
        StringBuilder sb = new StringBuilder();
        if (FileUtil.isEmpty(dir)) {
            return;
        }
        for (File file : dir.listFiles()) {
            byte[] bytes = FileUtil.readBytes(file);
            JSONObject result = test01(restTemplate, bytes, file.getName());
            if (result.getBoolean("identified")) {
                sb.append(file.getName())
                        .append('\t')
                        .append(result.getString("pid"))
                        .append('\t')
                        .append(result.getDouble("score"))
                        .append('\n');
            } else {
                sb.append(file.getName())
                        .append('\t')
                        .append("未识别")
                        .append('\t')
                        .append(0.0)
                        .append('\n');
            }
        }
        System.out.println(sb);

        // 人员登记
//        test02(restTemplate, bytes, 1622L);

        // 获取feature
//        String feature = test03(restTemplate, 1622L);
//        System.out.printf(feature);

        // 人员删除
//        test05(restTemplate, 171L);

        // 人脸探测
//        JSONObject jsonObject = test06(restTemplate, bytes, "big_2.jpg");

        // 获取人员信息
//        JSONObject result = test07(restTemplate, 245L);
//        System.out.println(result.toString());

    }

    /**
     * 人员搜索
     */
    public static JSONObject test01(RestTemplate restTemplate, byte[] bytes, String filename) {
        JSONObject result = new JSONObject();

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", Authorization);
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        String url = BASE_URL + PERSON_IDENTIFY + "?cuc_key=" + CUC_KEY;

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        ByteArrayResource byteArrayResource = new ByteArrayResource(bytes){
            @Override
            public String getFilename() {
                return filename;
            }
        };
        param.add("image", byteArrayResource);
        param.add("max_num_matches", 1);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        JSONObject jsonObject = restTemplate.postForObject(url, httpEntity, JSONObject.class);

//        System.out.println(jsonObject.toString());
        if ("success".equals(jsonObject.getString("status"))) {
            JSONArray results = jsonObject.getJSONArray("results");
            if (!results.isEmpty()) {
                JSONObject result1 = results.getJSONObject(0);
                JSONArray candidates = result1.getJSONArray("candidates");
                if (!candidates.isEmpty()) {
                    JSONObject candidate = candidates.getJSONObject(0);
                    result.put("identified", true);
                    result.put("pid", candidate.getString("person_label"));
                    result.put("score", candidate.getFloat("match_score_max"));
                } else {
                    result.put("identified", false);
                }
            } else {
                result.put("identified", false);
            }
        } else {
            result.put("identified", false);
        }

        return result;
    }

    /**
     * 人员登记
     */
    public static void test02(RestTemplate restTemplate, byte[] bytes, Long mid) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", Authorization);
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        String url = BASE_URL + PERSON_ENROLL + "?cuc_key=" + CUC_KEY;

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        ByteArrayResource byteArrayResource = new ByteArrayResource(bytes){
            @Override
            public String getFilename() {
                return String.format("%d.jpg", mid);
            }
        };
        param.add("image", byteArrayResource);
        param.add("person_label", 171);
        param.add("gallery_label", "szlx");
        param.add("face_label", mid);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        JSONObject jsonObject = restTemplate.postForObject(url, httpEntity, JSONObject.class);

        System.out.println(jsonObject.toString());
    }

    /**
     * 获取 feature
     */
    public static String test03(RestTemplate restTemplate, Long mid) {
        JSONObject result = new JSONObject();

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", Authorization);
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        String url = BASE_URL + GET_FACE_FEATURE + "?cuc_key=" + CUC_KEY;

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("face_label", mid);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        JSONObject jsonObject = restTemplate.postForObject(url, httpEntity, JSONObject.class);

        return jsonObject.getString("face_feature");
    }


    /**
     * 人员登记2
     */
    public static void test04(RestTemplate restTemplate, Long mid, String featureStr) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", Authorization);
        headers.setContentType(MediaType.APPLICATION_JSON);

        String url = BASE_URL + PERSON_ENROLL_FEATURE + "?cuc_key=" + CUC_KEY;

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("person_label", 171);
        param.add("face_label", mid);
        param.add("gallery_label", "szlx");
        param.add("feature", featureStr);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        JSONObject jsonObject = restTemplate.postForObject(url, httpEntity, JSONObject.class);

        System.out.println(jsonObject.toString());
    }

    /**
     * 删除人员
     */
    public static void test05(RestTemplate restTemplate, Long pid) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", Authorization);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        String url = BASE_URL + PERSON_DELETE + "?cuc_key=" + CUC_KEY;

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("person_label", pid);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        JSONObject jsonObject = restTemplate.postForObject(url, httpEntity, JSONObject.class);

        System.out.println(jsonObject.toString());
    }

    /**
     * 人脸探测
     */
    public static JSONObject test06(RestTemplate restTemplate, byte[] imgBytes, String fileName) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", Authorization);
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        String url = BASE_URL + FACE_DETECT + "?cuc_key=" + CUC_KEY;

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        ByteArrayResource byteArrayResource = new ByteArrayResource(imgBytes){
            @Override
            public String getFilename() {
                return fileName;
            }
        };
        param.add("image", byteArrayResource);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);

        return restTemplate.postForObject(url, httpEntity, JSONObject.class);
    }

    /**
     * 获取人员详情
     */
    public static JSONObject test07(RestTemplate restTemplate, Long pid) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", Authorization);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        String url = BASE_URL + PERSON_GET + "?cuc_key=" + CUC_KEY;

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("person_label", String.valueOf(pid));

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        JSONObject result = restTemplate.postForObject(url, httpEntity, JSONObject.class);

        return result;
    }

}
